﻿using System;
using System.Collections.Generic;
using System.Linq;
using Zj.HttpCodeDemo.ConsoleApp.DbFirst;

namespace Zj.HttpCodeDemo.ConsoleApp.Samples
{
    internal class EntityFrameworkDbFirstSample
    {
        internal static void Sample()
        {
            using (var ctx = new TestEntities())
            {
                //SeeData(ctx);
                //ctx.User.First().UserLoginErrLog.ToList().ForEach(l => Console.WriteLine($"\t{l.User.UserName}\t,于{l.LoginTime}\t在{l.IPAddress}\t登录"));
                ctx.UserLoginErrLog
                   .ToList()
                   .ForEach(l => Console.WriteLine($"\t{l.User.UserName}\t,于{l.LoginTime}\t在{l.IPAddress}\t登录"));
                //var list = from user in ctx.User
                //           join log in ctx.UserLoginErrLog
                //           on user.Id equals log.UserId
                //           select new
                //           {
                //               UserName = user.UserName,
                //               LoginTime = log.LoginTime,
                //               IPAddress = log.IPAddress
                //           };

                //var list = from log in ctx.UserLoginErrLog
                //           join user in ctx.User
                //           on log.UserId equals user.Id
                //           select new
                //           {
                //               UserName = user.UserName,
                //               LoginTime = log.LoginTime,
                //               IPAddress = log.IPAddress
                //           };
                //list.ToList()
                //    .ForEach(l => Console.WriteLine($"\t{l.UserName}\t,于{l.LoginTime}\t在{l.IPAddress}\t登录"));
            }
        }

        private static void SeeData(TestEntities ctx)
        {
            var user = new User()
            {
                UserName = "operator",
                Password = "123456"
            };

            ctx.User.Add(user);
            ctx.SaveChanges();//Add a user.

            var log = new UserLoginErrLog()
            {
                IPAddress = "192.168.9.14",
                LoginTime = DateTime.Now,
                UserId = user.Id
            };
            var log_ = new UserLoginErrLog()
            {
                IPAddress = "192.168.9.24",
                LoginTime = DateTime.UtcNow,
                UserId = user.Id
            };
            ctx.UserLoginErrLog.AddRange(new List<UserLoginErrLog>() { log, log_ });
            ctx.SaveChanges();//Add a user error log.
        }
    }
}